import express from "express";
import {
  Comment,
  Group,
  Inform,
  Message,
  Space,
  User,
  newsDB,
} from "../db/model.js";
import multer from "multer";
import { getUrl, upload } from "../cos.js";
import mongoose from "mongoose";


const router = express.Router();

let startTime = null;

function startTimer() {
  startTime = Date.now(); // 记录当前时间的毫秒数
}

function stopTimer() {
  if (startTime === null) {
    console.error("Timer has not been started.");
    return null;
  }

  const endTime = Date.now();
  const elapsedTime = endTime - startTime; // 计算经过的时间毫秒数
  startTime = null; // 重置开始时间

  return elapsedTime; // 返回经过的时间毫秒数
}

// 配置 multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/"); // 上传的文件将存储在 uploads 目录
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

const uploadind = multer({ storage: storage });

/* GET home page. */
router.get("/", async function (req, res, next) {
  // await Message.create({
  //     title: "今天天气好的",
  //     is_group: false,
  //     user: '668b9302f5542d7fe73ca91e',
  //     to_user: '668bd54eddfcac51543bf589',
  //     type:'text',
  //     group_name:null
  // })
  res.send({ msg: "这是服务器主页" });
});

router.get("/comment", async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const query = {};
    const data = await Comment.find(query)
      .populate("user")
      .populate("space")
      .skip(page)
      .limit(pageSize);
    res.status(200).send({ data });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.get("/message", async (req, res) => {
  try {
    startTimer();
    const { user_id, to_user_id } = req.query;
    // 创建匹配阶段，确保消息中包含登录用户或对方用户
    const matchStage = {
      $match: {
        $or: [
          {
            user: new mongoose.Types.ObjectId(user_id),
            to_user: new mongoose.Types.ObjectId(to_user_id),
          },
          {
            user: new mongoose.Types.ObjectId(to_user_id),
            to_user: new mongoose.Types.ObjectId(user_id),
          },
        ],
      },
    };
    const lookup = {
      $lookup: {
        from: "user",
        localField: "user",
        foreignField: "_id",
        as: "user",
      },
    };
    const lookup2 = {
      $lookup: {
        from: "user",
        localField: "to_user",
        foreignField: "_id",
        as: "to_user",
      },
    };
    // 可选：添加排序阶段，按时间戳升序或降序排序
    const sortStage = {
      $sort: {
        createdAt: 1, // 按时间戳升序排序，如果需要降序则使用 -1
      },
    };

    // 执行聚合查询
    const pipeline = [matchStage, sortStage, lookup, lookup2]; // 可根据需要添加其他阶段
    let messages = await Message.aggregate(pipeline).allowDiskUse(true);
    const timeTaken = stopTimer();
    console.log(`耗时：${timeTaken}ms`);
    // 处理查询结果

    res.status(200).send({ data: messages });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.get("/show_message", async (req, res) => {
  try {
    startTimer();
    const { userId } = req.query;

    // 创建匹配阶段，确保至少一个字段（user 或 to_user）包含 userId
    const matchStage = {
      $match: {
        $or: [
          { user: new mongoose.Types.ObjectId(userId) },
          { to_user: new mongoose.Types.ObjectId(userId) },
        ],
      },
    };

    // 添加一个假定的排序字段（例如 createdAt），并按照时间降序排序
    const sortStage = {
      $sort: {
        createdAt: -1,
      },
    };

    // 使用 $addFields 转换 createdAt 字段为时间戳（milliseconds）
    const addFieldsStage = {
      $addFields: {
        createdAtTimestamp: { $toLong: "$createdAt" },
      },
    };

    // 使用 $group 聚合阶段，对每一对 user 和 to_user 分组，并获取每组的最新消息
    const groupStage = {
      $group: {
        _id: {
          $cond: [
            { $gt: [{ $cmp: ["$user", "$to_user"] }, 0] },
            { user: "$user", to_user: "$to_user" },
            { user: "$to_user", to_user: "$user" },
          ],
        },
        message: { $first: "$$ROOT" }, // 获取每组的第一条消息（即最新消息）
      },
    };

    // 解构 group 阶段的结果，使输出格式与原始文档类似
    const replaceRootStage = {
      $replaceRoot: { newRoot: "$message" },
    };

    // 从 message 对象中提取字段，包括转换后的时间戳字段
    const projectStage = {
      $project: {
        _id: 1,
        type: 1,
        is_group: 1,
        group_name: 1,
        title: 1,
        img: 1,
        video: 1,
        user: 1,
        to_user: 1,
        createdAtTimestamp: 1, // 添加时间戳字段
        createdAt: 1, // 原始的 createdAt 字段仍然保留
      },
    };

    const lookup = {
      $lookup: {
        from: "user",
        localField: "user",
        foreignField: "_id",
        as: "user",
      },
    };
    const lookup2 = {
      $lookup: {
        from: "user",
        localField: "to_user",
        foreignField: "_id",
        as: "to_user",
      },
    };

    // 执行聚合查询
    const pipeline = [
      matchStage,
      sortStage,
      addFieldsStage,
      groupStage,
      replaceRootStage,
      projectStage,
      lookup,
      lookup2,
    ];
    let data = await Message.aggregate(pipeline).allowDiskUse(true);
    const timeTaken = stopTimer();
    console.log(`耗时：${timeTaken}ms`);
    res.status(200).send({ data });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});
const processData = async (data) => {
  // 创建一个 Promise 数组，每个 Promise 都是一个异步查询操作
  const newDataPromises = data.map(async (item) => {
    const user = await User.findOne({ _id: item.user }).lean();
    const to_user = await User.findOne({ _id: item.to_user }).lean();
    return { ...item, user, to_user };
  });

  // 等待所有异步操作完成
  const newData = await Promise.all(newDataPromises);

  // 返回处理后的数据
  return newData;
};
router.get("/group", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, search_key } = req.query;
    const query = {};
    const regexPattern = `.*${search_key}.*`;
    // 搜索
    if (search_key) {
      query.$or = [
        { name: { $regex: regexPattern, $options: "i" } },
        { account: { $regex: regexPattern, $options: "i" } },
      ];
    }
    const data = await Group.find(query)
      .populate("user")
      .skip(page)
      .limit(pageSize);
    res.status(200).send({ data });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.get("/users", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, search_key } = req.query;
    const query = {};
    const regexPattern = `.*${search_key}.*`;
    // 搜索
    if (search_key) {
      query.$or = [
        { name: { $regex: regexPattern, $options: "i" } },
        { account: { $regex: regexPattern, $options: "i" } },
      ];
    }
    const data = await User.find(query)
      .populate("space")
      .populate("group")
      .populate({
        path: "groups.members",
      });
    res.status(200).send({ data });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.get("/space", async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const query = {};
    const data = await Space.find(query)
      .populate("user")
      .populate("likes")
      .populate("comments")
      .skip(page)
      .limit(pageSize);

    res.status(200).send({ data });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.post("/upload", uploadind.single("file"), async (req, res) => {
  try {
    const file = req.file;

    const d = upload(file.filename, file.path);
    res.status(200).send({ data: d });
  } catch (err) {
    console.log(err);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.get("/inform", async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const query = {};
    const data = await Inform.find(query)
      .populate("sender")
      .populate("receiver");

    res.status(200).send({ data });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.get("/get_url", async (req, res) => {
  try {
    const { Key, Expired = 600 } = req.query;
    const url = await getUrl(Key, Expired);
    res.status(200).send({ data: url });
  } catch (e) {
    console.log(e);
    res.status(500).send({ msg: "服务器错误" });
  }
});

router.post("/getcode", (req, res) => {
  let { phone } = req.body;
  console.log(req.body);
  let code = randomCode(4); //生成6位数字随机验证码
  console.log(code);
  res.send({
    code: 200,
    codes: 8888,
  });
  sendCode(phone, code, (success) => {
    if (success) {
      res.send({
        code: 200,
        codes: code,
        message: "短信验证码已发送",
      });
    } else {
      res.send({
        code: 500,
        codes: code,
        message: "短信验证码发送失败",
      });
    }
  });
});
router.post("/addNews", async (req, res) => {
  let data = req.body;
  await newsDB.create(data);
  res.send({
    code: 200,
  });
});

router.get("/getTalk", async (req, res) => {
  let { user1, user2 } = req.query;
  let data = await newsDB
    .find({
      $or: [
        { senderId: user1, senderId2: user2 },
        { senderId: user2, senderId2: user1 },
      ],
    })
    .populate("product");
  res.send({
    code: 200,
    data,
  });
});
router.get("/getTalk2", async (req, res) => {
  let data = await newsDB.find();
  // console.log(data);
  res.send({
    code: 200,
    data,
  });
});



export default router;
